<?php

namespace app\common\service\sms;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use app\util\ReturnCode;
use think\facade\Cache;
use think\facade\Env;
use think\Response;

class AliSms
{
    /**
     * @param string $phone  手机号码
     * @param int $code  验证码
     * @return bool  true
     */
    public static function send(string $phone, int $code): Response
    {
        if (empty($phone) || empty($code)) {
            return json([
                'code' => ReturnCode::EMPTY_PARAMS,
                'msg'  => '手机号、验证码不能为空',
                'data' => []
            ]);
        }

        try {
            $templateParam = json_encode(['code' => $code]);
            // 创建客户端
            AlibabaCloud::accessKeyClient(config('alisms.AccessKeyId'), config('alisms.Secret'))
                ->regionId(config('alisms.RegionId'))
                ->asDefaultClient();
            // 发送请求
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host(config('alisms.Host'))
                ->options([
                    'query' => [
                        'RegionId' => config('alisms.RegionId'),
                        //需要发送到那个手机
                        'PhoneNumbers' => $phone,
                        //必填项 签名(需要在阿里云短信服务后台申请)
                        'SignName' => config('alisms.SignName'),
                        //必填项 短信模板code (需要在阿里云短信服务后台申请)
                        'TemplateCode' => config('alisms.TemplateCode'),
                        //如果在短信中添加了${code} 变量则此项必填 要求为JSON格式
                        'TemplateParam' => $templateParam,
                    ],
                ])
                ->request();
            $res = $result->toArray();
            if ($res['Code'] == 'OK') {
                Cache::set('code_cache'.$phone, $code, 180); // 有效期3分钟
                Cache::set('code_time'.$phone, time()+60, 60); // 1分钟内不能重复获取
                return json([
                    'code' => ReturnCode::SUCCESS,
                    'msg'  =>'验证码发送成功',
                    'data' => []
                ]);
            } else {
                return json([
                    'code' => ReturnCode::SERVICE_ERROR,
                    'msg'  => $res['Message'],
                    'data' => $res
                ]);
            }
        } catch (ServerException $e) {
            return json([
                'code' => ReturnCode::SERVICE_ERROR,
                'msg'  => $e->getErrorMessage(),
                'data' => []
            ]);
        } catch (ClientException $e) {
            return json([
                'code' => ReturnCode::CLIENT_ERROR,
                'msg'  => $e->getErrorMessage(),
                'data' => []
            ]);
        }
    }

    public static function check(string $phone, int $code) : bool
    {
        if (empty($phone) || empty($code)) {
            return false;
        }
        // 开发环境默认验证码
        if (Env::get('APP_DEBUG') && $code == 123456) {
            return true;
        }
        // 苹果审核账号
        if ($phone == '13712587485' && $code = 123456) {
            return true;
        }
        // 内部开发账号
        if (in_array($phone, ['17620729860', '16620363310']) && $code = 123456) {
            return true;
        }
        if (Cache::get("code_cache".$phone) != $code) {
            return false;
        }
        return true;
    }
}